package yiran.gui;


import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import yiran.depositcumulative.data.DatabaseService;
import yiran.depositcumulative.lang.LangHelper;

import java.util.ArrayList;
import java.util.List;

public class TopGUI {
    private static final int PAGE_SIZE = 45; // 每页显示45个玩家（5行）
    private final DatabaseService databaseService;
    private int currentPage = 1;
    private int totalPages = 1;

    public TopGUI(DatabaseService databaseService) {
        this.databaseService = databaseService;
    }

    public void open(Player player) {
        // 计算总页数
        totalPages = databaseService.getTotalPages(PAGE_SIZE);
        if (currentPage > totalPages) currentPage = totalPages;
        if (currentPage < 1) currentPage = 1;
        
        // 创建库存界面
        String title = LangHelper.getString("gui.title", currentPage, totalPages);
        Inventory gui = Bukkit.createInventory(null, 54, title);
        
        // 获取当前页数据
        List<DatabaseService.PlayerTotal> topPlayers =
            databaseService.getTopPlayers(currentPage, PAGE_SIZE);
        
        // 填充玩家数据
        for (int i = 0; i < topPlayers.size(); i++) {
            DatabaseService.PlayerTotal playerTotal = topPlayers.get(i);
            gui.setItem(i, createPlayerHead(playerTotal, i));
        }
        
        // 添加分页按钮
        gui.setItem(45, createNavigationItem("previous", LangHelper.getString("gui.previous_page")));
        gui.setItem(49, createNavigationItem("close", LangHelper.getString("gui.close")));
        gui.setItem(53, createNavigationItem("next", LangHelper.getString("gui.next_page")));
        
        // 添加信息面板
        gui.setItem(46, createInfoItem("cumulative", 
            LangHelper.getString("gui.total_players"), 
            String.valueOf(databaseService.getPlayersWithDeposits().size())));
        
        gui.setItem(47, createInfoItem("total", 
            LangHelper.getString("gui.total_points"), 
            String.valueOf(databaseService.getTotalDepositAll())));
        
        // 打开GUI
        player.openInventory(gui);
    }

    private ItemStack createPlayerHead(DatabaseService.PlayerTotal playerTotal, int currentIndex) {
        // 修复后的方法体
        Material headMaterial = Material.matchMaterial("PLAYER_HEAD");
        if (headMaterial == null) {
            headMaterial = Material.matchMaterial("SKULL_ITEM");
        }
        if (headMaterial == null) {
            headMaterial = Material.PAPER;
        }

        ItemStack head = new ItemStack(headMaterial);

        if (headMaterial.name().equals("SKULL_ITEM")) {
            head.setDurability((short) 3);
        }

        SkullMeta meta = (SkullMeta) head.getItemMeta();

        if (meta != null) {
            meta.setDisplayName(ChatColor.GOLD + playerTotal.getPlayerName());

            OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(playerTotal.getPlayerName());
            meta.setOwningPlayer(offlinePlayer);

            List<String> lore = new ArrayList<>();
            lore.add(ChatColor.GRAY + LangHelper.getString("gui.points") + ": " +
                    ChatColor.GREEN + playerTotal.getTotalPoints());

            int rank = (currentPage - 1) * PAGE_SIZE + currentIndex + 1;
            lore.add(ChatColor.GRAY + LangHelper.getString("gui.rank") + ": " +
                    ChatColor.YELLOW + rank);

            meta.setLore(lore);
            head.setItemMeta(meta);
        }
        return head;
    }
    
    private ItemStack createNavigationItem(String type, String name) {
        Material material;
        switch (type) {
            case "previous":
            case "next":
                material = Material.ARROW; break;
            case "close": material = Material.BARRIER; break;
            default: material = Material.PAPER;
        }
        
        ItemStack item = new ItemStack(material);
        ItemMeta meta = item.getItemMeta();
        
        if (meta != null) {
            meta.setDisplayName(name);
            item.setItemMeta(meta);
        }
        return item;
    }

    private ItemStack createInfoItem(String type, String title, String value) {
        Material material = Material.PAPER;

        if ("cumulative".equals(type)) {
            material = Material.BOOK;
        } else if ("total".equals(type)) {
            // 优先尝试 SUNFLOWER (1.14+)
            Material sunflower = Material.matchMaterial("SUNFLOWER");
            if (sunflower != null) {
                material = sunflower;
            } else {
                // 回退到 GOLD_INGOT (所有版本)
                material = Material.matchMaterial("GOLD_INGOT");
                if (material == null) {
                    // 非常旧的版本回退
                    material = Material.matchMaterial("GOLD_INGOT");
                }
            }
        }

        ItemStack item = new ItemStack(material);
        ItemMeta meta = item.getItemMeta();

        if (meta != null) {
            meta.setDisplayName(ChatColor.GOLD + title);

            List<String> lore = new ArrayList<>();
            lore.add(ChatColor.GREEN + value);
            meta.setLore(lore);

            item.setItemMeta(meta);
        }
        return item;
    }
    
    // 处理点击事件
    public void handleClick(int slot, Player player) {
        switch (slot) {
            case 45: // 上一页
                if (currentPage > 1) {
                    currentPage--;
                    open(player);
                }
                break;
                
            case 53: // 下一页
                if (currentPage < totalPages) {
                    currentPage++;
                    open(player);
                }
                break;
                
            case 49: // 关闭
                player.closeInventory();
                break;
        }
    }
}
